/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.boot.starter.middleware.config;

import io.iec.edp.caf.boot.starter.middleware.entity.CAFErrorPage;
import io.iec.edp.caf.boot.starter.middleware.entity.CAFErrorPageConfig;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;

/**
 * 自定义错误页配置
 * 也可以通过WebServerFactoryCustomizer扩展实现
 *
 * @author wangyandong
 * @date 2021/09/13 17:32
 * @email wangyandong@inspur.com
 */
public class CAFErrorPageRegistrar implements ErrorPageRegistrar {
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        //也可以通过自定义实现接口ErrorPageRegistrar来实现
        CAFErrorPageConfig config = SpringBeanUtils.getBean(CAFErrorPageConfig.class);
        ErrorPage[] pages = new ErrorPage[config.getPages().size()];
        int a = 0;
        for (CAFErrorPage pageConfig : config.getPages()) {
            ErrorPage page = new ErrorPage(HttpStatus.valueOf(Integer.parseInt(pageConfig.getStatus())), pageConfig.getPath());
            pages[a++] = page;
        }
        registry.addErrorPages(pages);
    }
}
